package com.coocaa.launcher.sidebar.left.item;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;

import com.coocaa.launcher.sidebar.left.LeftSideContainerLayout;
import com.coocaa.launcher.util.FrescoBitmapFactory;
import com.coocaa.launcher.wallpaper.WallpaperManager;
import com.coocaa.x.framework.utils.FastBlur;
import com.coocaa.x.framework.utils.ImageUtils;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;

/**
 * Created by luwei on 15-7-2.
 */
public class LeftSideItemContainerLayout extends LeftSideContainerLayout implements
        WallpaperManager.OnBackgroundChangeListener, FrescoBitmapFactory.OnBitmapLoadListener {

    private BitmapDrawable smallBg = null;

    public LeftSideItemContainerLayout(Context context) {
        super(context);
        WallpaperManager.getInstance().addBackgroundChangeListener(this);
        initBg();

    }

    private void initBg() {
        LogUtils.d("wallpaper", "init bg " + this.toString());
        WallpaperManager.getInstance().getBackground(R.drawable.bg_1, 384, 216, this);
    }

    @Override
    public void onBackgroundChange() {
        recycle();
        initBg();
    }

    private void recycle() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTempLayout.setBackgroundDrawable(null);
                if (smallBg != null && smallBg.getBitmap() != null && !smallBg.getBitmap().isRecycled()) {
                    smallBg.getBitmap().recycle();
                }
            }
        });

    }

    @Override
    public void destory() {
        recycle();
        WallpaperManager.getInstance().removeBackgroundChangeListener(this);
    }

    @Override
    public void loadSuccess(Bitmap bitmap, String url) {
        smallBg = new BitmapDrawable(ImageUtils.changeBitmapBrightness(FastBlur.doBlur(Bitmap.createBitmap(
                        bitmap, 0, 0, 100, 216), 20, true
        ), 0.7f, 0));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTempLayout.setBackgroundDrawable(smallBg);
            }
        });
    }

    @Override
    public void loadFailed(String url) {
        WallpaperManager.getInstance().getResourceBitmap(R.drawable.bg_1, 384, 216, this);
    }
}
